package com.xunshangwang.pinhaohuo.ui.fragments;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.loopj.android.http.RequestParams;
import com.xunshangwang.pinhaohuo.R;
import com.xunshangwang.pinhaohuo.app.MainApplication;
import com.xunshangwang.pinhaohuo.entity.Account;
import com.xunshangwang.pinhaohuo.entity.OrderCount;
import com.xunshangwang.pinhaohuo.http.HttpTool;
import com.xunshangwang.pinhaohuo.http.JsonHttpHandler;
import com.xunshangwang.pinhaohuo.tools.DebugHelper;
import com.xunshangwang.pinhaohuo.transformation.CircleTransformation;
import com.xunshangwang.pinhaohuo.ui.activities.AfterSaleServiceActivity;
import com.xunshangwang.pinhaohuo.ui.activities.MainActivity;
import com.xunshangwang.pinhaohuo.ui.activities.MyAddressActivity;
import com.xunshangwang.pinhaohuo.ui.activities.MyCollectionActivity;
import com.xunshangwang.pinhaohuo.ui.activities.OrderListActivity;
import com.xunshangwang.pinhaohuo.widgets.LoadLayout;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.SocketHandler;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import cz.msebera.android.httpclient.Header;
import tool.library.ToastTool;

/**
 * Created by xzp on 16/1/21.
 */
public class PersonalCenterFragment extends BaseFragment implements View.OnClickListener,PlatformActionListener,Handler.Callback{
    private int[] mFunctionDrawables={R.drawable.my_collection_icon,R.drawable.my_address_icon,
            R.drawable.after_pay_service_icon,R.drawable.clear_cache_icon,R.drawable.about_us_icon};
    private int[] mOrderFunctionDrawables={R.drawable.order_all_icon,R.drawable.order_pay_icon,R.drawable.order_delivery_icon,
            R.drawable.order_receiving_icon};
    private ImageView mHeadPortraitImage;
    private LoadLayout mLoad;
    private TextView mUserNameText;
    private Handler mHandler=new Handler(this);
    private View mLogoutBtn;
    private List<TextView> mOrderNumTextList;
    private final String ORDER_REQUEST_TAG="OrderRequest";
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_personal_center,container,false);
        LinearLayout orderFunctionLayout= (LinearLayout) view.findViewById(R.id.order_function_layout);
        String[] orderFunctionList=inflater.getContext().getResources().getStringArray(R.array.order_function_list);
        mOrderNumTextList=new ArrayList<TextView>();
        for(int i=0;i<4;i++){
            ViewGroup child= (ViewGroup) orderFunctionLayout.getChildAt(i);
            child.setOnClickListener(this);
            child.setTag(i);
            ImageView functionIcon= (ImageView) child.findViewById(R.id.order_function_icon);
            functionIcon.setImageResource(mOrderFunctionDrawables[i]);
            TextView functionText= (TextView) child.findViewById(R.id.order_function_name_text);
            functionText.setText(orderFunctionList[i]);
            TextView numText= (TextView) child.findViewById(R.id.order_function_num_text);
            numText.setVisibility(View.INVISIBLE);
            mOrderNumTextList.add(numText);
        }
        LinearLayout contentLayout= (LinearLayout) view.findViewById(R.id.personal_center_content_layout);
        String[] functionList=inflater.getContext().getResources().getStringArray(R.array.personal_center_function_list);
        for(int i=0;i<5;i++){
            ViewGroup child= (ViewGroup) contentLayout.getChildAt(i+1);
            child.setOnClickListener(this);
            ImageView functionIcon= (ImageView) child.getChildAt(0);
            functionIcon.setImageResource(mFunctionDrawables[i]);
            TextView functionText= (TextView) child.getChildAt(1);
            functionText.setText(functionList[i]);
            ImageView arrowIcon= (ImageView) child.getChildAt(2);
            arrowIcon.setColorFilter(ContextCompat.getColor(inflater.getContext(),R.color.light_gray));
        }
        mHeadPortraitImage= (ImageView) view.findViewById(R.id.user_head_portrait_image);
        mUserNameText= (TextView) view.findViewById(R.id.user_name_text);
        mLoad= (LoadLayout) view.findViewById(R.id.load_layout);
        mLogoutBtn=view.findViewById(R.id.logout_btn);
        mLogoutBtn.setOnClickListener(this);
        mHeadPortraitImage.setOnClickListener(this);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if(getMainApplication().isLogin()){
            login();
        }
        else {
            logout();
        }
    }
    private void login(){
        Glide.with(this).load(getMainApplication().getAccount().getHeadimgurl()).transform(new CircleTransformation(getContext()))
                .into(mHeadPortraitImage);
        mUserNameText.setText(getMainApplication().getAccount().getNickname());
        mLogoutBtn.setVisibility(View.VISIBLE);

    }
    public void logout(){
        HttpTool.cancelRequests(ORDER_REQUEST_TAG);
        for(int i=0;i<mOrderNumTextList.size();i++){
            mOrderNumTextList.get(i).setVisibility(View.INVISIBLE);
        }
        mHeadPortraitImage.setImageResource(R.drawable.login_btn_image);
        mUserNameText.setText("立即登录");
        mLogoutBtn.setVisibility(View.GONE);
    }
    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id){
            case R.id.user_head_portrait_image:
                if(getMainApplication().isLogin())
                    break;
                mLoad.startLoad();
                Wechat wechat= (Wechat) ShareSDK.getPlatform(Wechat.NAME);
                wechat.setPlatformActionListener(this);
                wechat.showUser(null);
                break;
            case R.id.logout_btn:
                AlertDialog.Builder builder=new AlertDialog.Builder(getContext());
                builder.setMessage("你确定要注销吗");
                builder.setNegativeButton("取消", null);
                builder.setPositiveButton("立即注销", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getMainApplication().setAccount(null);
                        logout();
                        MainActivity activity= (MainActivity) getActivity();
                        activity.logout();
                    }
                });
                builder.show();
                break;
            case R.id.after_pay_service_btn:
                startActivity(new Intent(getContext(), AfterSaleServiceActivity.class));
                break;
            case R.id.clear_cache_btn:
                AlertDialog.Builder cacheBuilder=new AlertDialog.Builder(getContext());
                cacheBuilder.setMessage("你确定清理缓存吗?");
                cacheBuilder.setPositiveButton("立即清理", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Thread thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Glide.get(getContext()).clearDiskCache();
                                mHandler.sendEmptyMessage(10);
                            }
                        });
                        thread.start();
                        mLoad.startLoad();
                    }
                });
                cacheBuilder.setNegativeButton("取消",null);
                cacheBuilder.show();
                break;
            default:
                onAccountFunctionClick(v,id);
                break;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        requestOrderNum();
    }
    private void requestOrderNum(){
        if(getMainApplication().isLogin()){
            JsonHttpHandler<OrderCount> httpHandler=new JsonHttpHandler<OrderCount>() {
                @Override
                public OrderCount parseData(JSONObject object) throws Throwable {
                    return JSON.parseObject(object.getString("orders_count"),OrderCount.class);
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, OrderCount errorResponse) {
                    //super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, OrderCount response) {
                    if(response!=null){
                        mOrderNumTextList.get(1).setText(String.valueOf(response.getWait_pay()<100?response.getWait_pay():99));
                        mOrderNumTextList.get(1).setVisibility(response.getWait_pay()==0?View.INVISIBLE:View.VISIBLE);
                        mOrderNumTextList.get(2).setText(String.valueOf(response.getWait_send()<100?response.getWait_send():99));
                        mOrderNumTextList.get(2).setVisibility(response.getWait_send() == 0 ? View.INVISIBLE : View.VISIBLE);
                        mOrderNumTextList.get(3).setText(String.valueOf(response.getSending()<100?response.getSending():99));
                        mOrderNumTextList.get(3).setVisibility(response.getSending() == 0 ? View.INVISIBLE : View.VISIBLE);
                    }
                }
            };
            httpHandler.setTag(ORDER_REQUEST_TAG);
            HttpTool.get(getContext(), "?g=Api&m=Weuser&a=orders_count&token=" + getMainApplication().getToken(), httpHandler);
        }

    }
    @Override
    public void onStop() {
        super.onStop();
        HttpTool.cancelRequests(ORDER_REQUEST_TAG);
    }

    public void onAccountFunctionClick(View view,int id){
        if(!getMainApplication().isLogin()){
            ToastTool.showToast("请登录后再试");
            return;
        }
        switch (id){
            case R.id.my_collection_btn:
                startActivity(new Intent(getContext(), MyCollectionActivity.class));
                break;
            case R.id.my_address_btn:
                startActivity(new Intent(getContext(),MyAddressActivity.class));
                break;
            case R.id.order_all_btn:
            case R.id.order_pay_btn:
            case R.id.order_delivery_btn:
            case R.id.order_receiving_btn:
                Intent orderIntent=new Intent(getContext(), OrderListActivity.class);
                orderIntent.putExtra("position", (int) view.getTag());
                startActivity(orderIntent);
                break;
        }
    }
    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what){
            case 0:
                HashMap<String, Object> hashMap= (HashMap<String, Object>) msg.obj;
                requestLogin(hashMap);
                break;
            case 1:
                mLoad.finishLoad();
                ToastTool.showToast("登录失败，请重试");
                break;
            case 2:
                mLoad.finishLoad();
                break;
            case 10:
                mLoad.finishLoad();
                ToastTool.showToast("清理缓存成功");
                break;
        }
        return true;
    }
    private void requestLogin(HashMap<String, Object> hashMap){
        RequestParams params=new RequestParams();
        params.put("openid",hashMap.get("openid").toString());
        params.put("nickname",hashMap.get("nickname").toString());
        params.put("sex", TextUtils.equals("1", hashMap.get("sex").toString()) ? "男" : "女");
        params.put("headimgurl", hashMap.get("headimgurl").toString());
        params.put("unionid", hashMap.get("unionid").toString());
        JsonHttpHandler<Account> handler=new JsonHttpHandler<Account>() {
            @Override
            public void onFinish() {
                super.onFinish();
                mLoad.finishLoad();
            }

            @Override
            public Account parseData(JSONObject object) throws Throwable {
                return JSON.parseObject(object.toString(),Account.class);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Account response) {
                if(response==null)
                    ToastTool.showToast("登录失败,请重试");
                else {
                    getMainApplication().setAccount(response);
                    login();
                    requestOrderNum();
                }
            }
        };
        handler.setTag(getView());
        HttpTool.post(getContext(),"?g=Api&m=Wechat&a=app_login",params,handler);
    }
    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        Message message=mHandler.obtainMessage(0, hashMap);
        mHandler.sendMessage(message);
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
       mHandler.sendEmptyMessage(1);
    }

    @Override
    public void onCancel(Platform platform, int i) {
        mHandler.sendEmptyMessage(2);
    }
}
